import { ReqPage } from "@/api/interface";
import { serviceList, serviceRemove, serviceStart, serviceStop } from "@/api/modules/service/service";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/OnlineStatus/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { ServiceStatusTypes } from "@/enums/statusEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { GlobalStore } from "@/stores";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import AppletImg from "./../../../assets/images/applet/applet.png";
import DockerImg from "./../../../assets/images/applet/docker.png";
import BasicDialog from "./components/detailDialog";
import LoggerDialog from "./components/loggerDialog";
import { gotoPage } from "../../../utils/routerUtil";
import { RouterPath } from "@/enums/routerPath";
import { getDictObj } from "@/utils/cacheUtil";
export default defineComponent({
	setup() {
		const globalStore = GlobalStore();
		const serviceStatusLabels = ref<any>({});
		const initParam = reactive<ReqPage>({
			pageIndex: 0,
			pageSize: 20
		});

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return serviceList(params);
		};
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
			serviceStatusLabels.value = await getDictObj("service_status");
		});
		const detailDialog = reactive<any>({
			detail: {},
			title: "",
			visible: false
		});
		const loggerDialog = reactive<any>({
			detail: {},
			title: "服务日志",
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			if (row.id && !row.selectList) {
				row = { selectList: [row], selectedListIds: [row.id] };
			}
			switch (fn) {
				case "add":
					detailDialog.detail = { svcType: "applet", machine: "local" };
					detailDialog.title = "添加本地服务";
					detailDialog.visible = true;
					break;
				case "add-remote":
					detailDialog.detail = { svcType: "applet" };
					detailDialog.title = "添加远程服务";
					detailDialog.visible = true;
					break;
				case "mod":
					if (row.selectList.length != 1) {
						showMsg("请选择一个服务进行修改。", MessageType.warning);
						return;
					}
					detailDialog.detail = { ...row.selectList[0] };
					detailDialog.title = "修改服务";
					detailDialog.visible = true;
					break;
				case "detail":
					if (row.selectList.length != 1) {
						showMsg("请选择一个服务进行修改。", MessageType.warning);
						return;
					}
					detailDialog.detail = { ...row.selectList[0], readonly: true };
					detailDialog.title = "服务信息";
					detailDialog.visible = true;
					break;
				case "del":
					submitDel(row.selectList);
					break;
				case "stop":
					stop(row);
					break;
				case "start":
					start(row);
					break;
				case "logger":
					if (row.selectList && row.selectList.length != 1) {
						showMsg("请选择一个服务查看日志。", MessageType.warning);
						return;
					}
					let info = { ...((row.selectList && row.selectList[0]) || row.row) };
					loggerDialog.title = "【" + info.name + "】运行日志";
					loggerDialog.detail = info;
					loggerDialog.visible = true;
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "status", label: "状态", width: 100 },
			{ prop: "name", label: "服务名称", width: "230px", align: "left", search: { el: "input" } },
			{ prop: "bin", label: "程序", width: "130px" },
			{ prop: "instanceId", label: "服务标识", width: "180px", search: { el: "input" } },
			{ prop: "arg", label: "启动参数", width: "170px" },
			{ prop: "path", label: "运行路径", width: "180px" },
			{ prop: "updateTime", label: "更新时间", width: "170px" },
			{ prop: "loginTime", label: "登录时间", width: "170px" },
			{ prop: "machine", label: "部署节点", width: "130px" },
			{ prop: "version", label: "版本", width: "130px" },
			{ prop: "ip", label: "IP", width: "130px" },
			{ prop: "operate", label: "操作", fixed: "right", width: 100 }
		];

		const proTable = ref<any>();
		const start = async (data: any) => {
			if (!data.selectList[0]) {
				showMsg("请选择要操作的服务", MessageType.warning);
				return;
			}
			let { code } = await serviceStart({ id: data.selectList[0].id });
			showTips(code, "服务重启") && proTable.value.getTableList();
		};
		const stop = async (data: any) => {
			if (!data.selectList[0]) {
				showMsg("请选择要操作的服务", MessageType.warning);
				return;
			}
			let { code } = await serviceStop({ id: data.selectList[0].id });
			showTips(code, "停止服务") && proTable.value.getTableList();
		};
		const submitDel = async (dataList: any[]) => {
			if (!dataList.length) {
				showMsg("请选择要删除的服务", MessageType.warning);
				return;
			}
			confirm({ content: "删除服务后无法找回，确定进行当前操作" }).then(async flag => {
				if (!flag) {
					return;
				}
				let { code } = await serviceRemove({ id: dataList.map(item => item.id).join(",") });
				let ok = showTips(code, `删除服务`);
				if (ok) {
					proTable.value.clearSelection();
					proTable.value.reset();
				}
			});
		};
		const submitAdd = () => {
			detailDialog.visible = false;
			proTable.value.reset();
		};

		//上传网关程序
		const uploadParam = reactive({
			data: { id: "" },
			headers: { Authentication: "" }
		});
		const beforeUpload = (data: any) => {
			if (data.selectList.length != 1) {
				showMsg("请选择一个服务进行更新程序。", MessageType.warning);
				return;
			}
			uploadParam.data.id = data.selectList[0].id;
			uploadParam.headers.Authentication = globalStore.token;
			return true;
		};
		const uploadGatewaySuccess = async (res: any) => {
			let { code, message } = res;
			let ok = showTips(code, "程序更新", message);
			if (ok) {
				proTable.value.reset();
			}
		};
		const uploadGatewayError = async () => {
			showMsg("程序更新失败", false);
		};
		return () => {
			return (
				<div>
					{detailDialog.visible && (
						<BasicDialog
							width="700px"
							title={detailDialog.title}
							v-model:visible={detailDialog.visible}
							detail={detailDialog.detail}
							onSubmit={() => submitAdd()}
						/>
					)}
					<LoggerDialog
						width="1024px"
						title={loggerDialog.title}
						v-model:visible={loggerDialog.visible}
						detail={loggerDialog.detail}
						footerLabel={["关闭"]}
					/>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : "服务管理"}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							tableHeader: (scope: any) => {
								return (
									<>
										{/* 添加权限：分类 */}
										{buttonsList.value.find((item: any) => item.btnGroup == "add") ? (
											<el-dropdown
												v-slots={{
													dropdown: () => {
														return (
															<el-dropdown-menu>
																{buttonsList.value
																	.filter((btn: any) => btn.btnGroup == "add")
																	.map((btn: any) => {
																		return (
																			<el-dropdown-item onClick={() => clickBtn(btn.path, scope)}>
																				{btn.menuName}
																			</el-dropdown-item>
																		);
																	})}
															</el-dropdown-menu>
														);
													}
												}}
											>
												<el-button type="primary" class="mr-2">
													添加
													<el-icon class="el-icon--right">
														<arrow-down />
													</el-icon>
												</el-button>
											</el-dropdown>
										) : null}

										{/* 其他按钮权限 */}
										{buttonsList.value?.map((item: any) => {
											return (
												<>
													{item.path == "upload" ? (
														<el-upload
															style="margin-left: 15px;float: right;"
															headers={uploadParam.headers}
															show-file-list={false}
															action="/api/service/bin/upload"
															before-upload={() => beforeUpload(scope)}
															on-success={uploadGatewaySuccess}
															on-error={uploadGatewayError}
															name="file"
															data={uploadParam.data}
														>
															<el-button class="iconfont iconbx-upload">{item.menuName}</el-button>
														</el-upload>
													) : item.btnGroup == "add" ? null : (
														<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
															<i class={`iconfont ${item.icon}`}></i>
															{item.menuName}
														</el-button>
													)}
												</>
											);
										})}
									</>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										labels={serviceStatusLabels.value}
										onlineLabel="未知"
										offlineLabel="未知"
										types={ServiceStatusTypes}
										v-model={scope.row.status}
									></OnlineStatus>
								);
							},
							name: (scope: any) => {
								return (
									<el-link type="primary" onClick={() => clickBtn("detail", scope.row)}>
										<img style="height:18px;" src={scope.row.svcType == "dockerapp" ? DockerImg : AppletImg}></img>
										<span class="pl-2">{scope.row.name}</span>
									</el-link>
								);
							},
							loginTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							updateTime: (scope: any) => {
								return dataFormat("datetime", scope.row.updateTime);
							},
							machine: (scope: any) => {
								return scope.row.machine == "local" ? (
									<span>{scope.row.machine}</span>
								) : (
									<el-link onClick={() => gotoPage(RouterPath.gatewayDetail, { sn: scope.row.machine })}>
										<span class="pl-2">{scope.row.machine}</span>
									</el-link>
								);
							},
							arg: (scope: any) => {
								return (
									<>
										{scope.row.arg ? (
											<span>
												<el-tooltip show-after={500} content="复制启动命令">
													<i
														class="cursor-pointer iconfont iconbx-copy-alt pr-2"
														v-copy={`${scope.row.name} ${scope.row.arg}`}
													></i>
												</el-tooltip>
												<span>{scope.row.arg}</span>
											</span>
										) : (
											"--"
										)}
									</>
								);
							},
							operate: (scope: any) => {
								return (
									<>
										<el-link type="primary" link class="iconfont iconbx-file" onClick={() => clickBtn("logger", scope)}>
											日志
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											subtitle="当前没有任何运行中的服务，您可以添加和上传服务程序来启动相关服务功能。"
											btnText="添加服务"
											onClick={(scope: any) => clickBtn("add", scope)}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
